;$(function () {

    layui.use(['form', 'laydate', 'table', 'element'], function () {
        var table = layui.table,
            form = layui.form,
            laydate = layui.laydate,
            $ = layui.jquery,
            element = layui.element;

        let nowDate = getNowAndFormatDate();
        let now = {};
        now[nowDate] = "今天";
        let weekDate = getWeekAndFormatDate();
        let showDate = weekDate + " 00:00:00 - " + nowDate + " 23:59:59";
        laydate.render({
            elem: '#reduceReportDate'
            , range: true
            , trigger: 'click'
            , type: 'datetime'
            , mark: now
            , value: showDate
            , done: function (value) {
                $("#reduceReportDate").val(value);
                $("#reduceReportSearchBtn").click();
            }
        });
        laydate.render({
            elem: '#reduceReportDetailsDate'
            , range: true
            , trigger: 'click'
            , type: 'datetime'
            , mark: now
            // , value: showDate
            , done: function (value) {
                $("#reduceReportDetailsDate").val(value);
                let url = "toReduceReportDetails";
                let jsonData = [];
                let searchWaresId = $("#reduceReportDetailsWaresId").val();
                jsonData.push({"waresId": searchWaresId}, {"date": value});
                pageSkipping(url, jsonData);
            }
        });

        $(".layui-btn.layui-btn-primary.dateChoose").on('click', function () {
            let event = $(this).attr("lay-event");
            let dateValue;
            let nowDate = getNowAndFormatDate();
            switch (event) {
                case 'today':
                    dateValue = nowDate + " 00:00:00 - " + nowDate + " 23:59:59";
                    break;
                case 'yesterday':
                    let yesterday = getYesterdayAndFormatDate();
                    dateValue = yesterday + " 00:00:00 - " + yesterday + " 23:59:59";
                    break;
                case 'lastWeek':
                    let lastWeek = getWeekAndFormatDate();
                    dateValue = lastWeek + " 00:00:00 - " + nowDate + " 23:59:59";
                    break;
                case 'lastMonth':
                    let lastMonth = getMouthAndFormatDate();
                    dateValue = lastMonth + " 00:00:00 - " + nowDate + " 23:59:59";
                    break;
                case 'lastYear':
                    let lastYear = getYearAndFormatDate();
                    dateValue = lastYear + " 00:00:00 - " + nowDate + " 23:59:59";
                    break;
            }
            $("#reduceReportDate").val(dateValue);
            $("#reduceReportSearchBtn").click();
            form.render();
        });

        $("#reduceReportSearchBtn").on('click', function () {
            let searchDate = $("#reduceReportDate").val();
            let searchWaresId = $("#reduceReportSearchByWaresId").val();
            getReduceReportEChartsData();
            table.reload('reduceReportRender', {
                where: {
                    searchDate: searchDate
                    , searchWaresId: searchWaresId
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
        table.render({
            elem: '#reduceReportTable',
            url: 'getReduceReport',
            method: "post",
            response: {
                statusCode: true
            },
            where: {
                searchDate: $("#reduceReportDate").val(),
                searchWaresId: $("#reduceReportSearchByWaresId").val()
            },
            defaultToolbar: [],
            cellMinWidth: 80,
            cols: [[
                {field: 'sorts', title: '序号', templet: '#sort', width: 58, align: 'center'}
                , {field: 'waresId', title: '商品编码', align: 'center'}
                , {field: 'waresName', title: '商品名', align: 'center'}
                , {field: 'unit', title: '单位', align: 'center', width: 100}
                , {field: 'category', title: '分类', align: 'center', width: 180}
                , {field: 'orderNumber', title: '总退货数量', align: 'center'}
                , {
                    field: 'unitPrice', title: '总金额(元)', align: 'center', templet: function (d) {
                        return d.unitPrice.toFixed(2);
                    }
                }
                , {
                    field: 'tool', title: '操作', align: 'center', width: 120,
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="details">详情</span>'
                    }
                }
            ]],
            id: 'reduceReportRender',
            page: true
        });
        table.on('tool(reduceReportTable)', function (obj) {
            let data = obj.data;
            let date1 = $("#reduceReportDate").val();
            if (obj.event === "details") {
                let url = "toReduceReportDetails";
                let jsonData = [];
                jsonData.push({"waresId": data.waresId}, {"date": date1});
                pageSkipping(url, jsonData);
            }
        });

        table.render({
            elem: '#reduceReportDetailsTable',
            url: 'getReduceReportDetails',
            method: "post",
            response: {
                statusCode: true
            },
            where: {
                searchDate: $("#reduceReportDetailsDate").val(),
                searchWaresId: $("#reduceReportDetailsWaresId").val()
            },
            defaultToolbar: [],
            cellMinWidth: 80,
            cols: [[
                {field: 'sorts', title: '序号', templet: '#sort', width: 58, align: 'center'}
                , {field: 'unit', title: '订单号', align: 'center'}
                , {field: 'createDate', title: '入库时间', align: 'center'}
                , {field: 'orderNumber', title: '退货数量', align: 'center'}
                , {
                    field: 'unitPrice', title: '退货单价(元)', align: 'center', templet: function (d) {
                        return d.unitPrice.toFixed(2);
                    }
                }
                , {
                    field: 'amount', title: '退货金额(元)', align: 'center', templet: function (d) {
                        return (d.unitPrice * d.orderNumber).toFixed(2);
                    }
                }
            ]],
            id: 'reduceReportDetailsRender',
            page: true
        });
        $(".reduceReportTableBack").on('click', function () {
            window.location.href = "toReduceReport";
        });

        //初始化ehcharts实例
        getReduceReportEChartsData();

        //指定图表的配置项和数据
        function getReduceReportEChartsData() {
            if (isEmpty(document.getElementById("reduceReportTrendECharts"))) {
                return;
            }
            let reduceReportTrendECharts = echarts.init(document.getElementById("reduceReportTrendECharts"));
            let reduceReportPieECharts = echarts.init(document.getElementById("reduceReportPieECharts"));
            window.onresize = function () {
                //随浏览器缩放
                reduceReportTrendECharts.resize();
            };
            $.ajax({
                url: 'getChartsData',
                type: "post",
                dataType: "json",
                data: {date: $("#reduceReportDate").val()},
                async: false,
                success: function (result) {
                    if (result.code === true) {

                        $("#reduceReportCard1").html(result.reduceReportCard1 + '单');
                        $("#reduceReportCard2").html('￥' + result.reduceReportCard2.toFixed(2));

                        let charts1X = [];
                        let charts1Y = [];
                        let trendData = result.trendData;
                        for (let i = 0; i < trendData.length; i++) {
                            charts1X.push(trendData[i]["name"]);
                            charts1Y.push(trendData[i]["value"]);
                        }
                        let option = ({
                            // dataZoom: [{
                            //     type: 'slider',
                            //     show: true,
                            //     start: 0,
                            //     end: 30,
                            //     handleSize: 3
                            // },
                            //     {
                            //         type: 'inside',
                            //         start: 0,
                            //         end: 50
                            //     }
                            // ],
                            title: {
                                show: trendData.length === 0,
                                extStyle: {
                                    color: "black",
                                    fontSize: 20
                                },
                                text: "暂无数据",
                                left: "center",
                                top: "center"
                            },
                            tooltip: {trigger: "axis"},
                            grid: {
                                show: !0,
                                top: "35px",
                                left: "60px",
                                right: "20px",
                                bottom: "30px",
                                containLabel: false,
                                borderWidth: 0
                            },
                            xAxis: {
                                type: "category",
                                axisLine: {show: true, lineStyle: {color: "#000000"}},
                                data: charts1X,
                                axisLabel: {
                                    formatter: function (value) {
                                        return value.split(" ").join("\n");
                                    }
                                },
                            },
                            yAxis: {
                                name: "单位（元）",
                                type: "value",
                                offset: 8,
                                axisLine: {show: true, lineStyle: {color: "#000000"}},
                                splitLine: {show: true, lineStyle: {type: "dashed", color: "#e8e6f1"}},
                            },
                            backgroundColor: "#ffffff",
                            series: [{
                                type: "line",
                                name: "退货金额",
                                symbolSize: 7,
                                lineStyle: {normal: {color: "#1ca1fe", width: 2}},
                                itemStyle: {normal: {color: "#1ca1fe", label: {show: true}}},
                                data: charts1Y
                                // data: result.trendData
                            }]
                        });
                        reduceReportTrendECharts.setOption(option);
                        let option1 = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} 元'
                                // formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'vertical',
                                left: 10,
                            },
                            series: [
                                {
                                    name: '退货花费',
                                    type: 'pie',
                                    radius: ['45%', '70%'],
                                    avoidLabelOverlap: true,//防止重叠
                                    label: {
                                        normal: {
                                            formatter: '{b}:({d}%)',
                                            textStyle: {
                                                fontWeight: 'normal',
                                                fontSize: 15
                                            },
                                        },
                                        emphasis: {
                                            show: true,
                                            textStyle: {
                                                fontSize: '20',
                                                fontWeight: 'bold'
                                            }
                                        }
                                    },
                                    labelLine: {
                                        normal: {
                                            show: true
                                        }
                                    },
                                    data: result.pieData
                                }
                            ]
                        };

                        reduceReportPieECharts.setOption(option1);
                    } else {
                        layer.msg(result.msg);
                    }
                },
            });

        }
    });

});